import 'package:flutter/material.dart';
import 'package:ct_pa_majordomo/pages/mine/online_pay/state/online_pay_state.dart';
import 'package:ct_pa_majordomo/config/theme_vars.dart';
import 'package:ct_pa_majordomo/widgets/normal_scaffold/index.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

class EnterpriseSettlementPage extends StatefulWidget {
  final OnlinePayState state;
  final VoidCallback onStateChanged;
  final bool isReadOnly;

  const EnterpriseSettlementPage({
    super.key,
    required this.state,
    required this.onStateChanged,
    this.isReadOnly = false,
  });

  @override
  State<EnterpriseSettlementPage> createState() => _EnterpriseSettlementPageState();
}

class _EnterpriseSettlementPageState extends State<EnterpriseSettlementPage> {
  final _formKey = GlobalKey<FormState>();
  final _bankNameController = TextEditingController();
  final _bankAccountController = TextEditingController();
  String _settlementType = '';

  // 结算类型字典
  static const Map<String, String> _settlementTypeMap = {
    '1': '法人账户',
    '2': '对公账户',
  };

  @override
  void initState() {
    super.initState();
    _bankNameController.text = widget.state.company["bankName"] ?? '';
    _bankAccountController.text = widget.state.company["bankAccount"] ?? '';
    _settlementType = widget.state.company["settlementType"] ?? '';
  }

  @override
  void dispose() {
    _bankNameController.dispose();
    _bankAccountController.dispose();
    super.dispose();
  }

  void _showAccountTypeOptions() {
    if (widget.isReadOnly) return;
    
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.white,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      builder: (BuildContext context) {
        return Container(
          padding: const EdgeInsets.all(16),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 标题栏
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  const Text(
                    '选择账户类型',
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  IconButton(
                    onPressed: () => Navigator.pop(context),
                    icon: const Icon(Icons.close),
                  ),
                ],
              ),
              const SizedBox(height: 16),
              // 选项列表
              ..._settlementTypeMap.entries.map((entry) => _buildOptionItem(
                value: entry.key,
                label: entry.value,
                isSelected: _settlementType == entry.key,
              )),
              const SizedBox(height: 16),
            ],
          ),
        );
      },
    );
  }

  Widget _buildOptionItem({
    required String value,
    required String label,
    required bool isSelected,
  }) {
    return Container(
      margin: const EdgeInsets.only(bottom: 8),
      decoration: BoxDecoration(
        border: Border.all(
          color: isSelected ? ThemeVars.colorPrimary : ThemeVars.colorBorder,
          width: isSelected ? 2 : 1,
        ),
        borderRadius: BorderRadius.circular(8),
        color: isSelected ? ThemeVars.colorPrimary.withOpacity(0.1) : Colors.white,
      ),
      child: ListTile(
        title: Text(
          label,
          style: TextStyle(
            color: isSelected ? ThemeVars.colorPrimary : Colors.black,
            fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
          ),
        ),
        trailing: isSelected
            ? Icon(
                Icons.check_circle,
                color: ThemeVars.colorPrimary,
              )
            : null,
        onTap: () {
          setState(() {
            _settlementType = value;
          });
          Navigator.pop(context);
        },
      ),
    );
  }

  Future<void> _saveForm() async {
    if (!_formKey.currentState!.validate()) {
      return;
    }

    if (_settlementType.isEmpty) {
      EasyLoading.showError('请选择账户类型');
      return;
    }

    EasyLoading.show(status: "保存中...");

    try {
      widget.state.updateCompanySettlementInfo(
        settlementType: _settlementType,
        bankName: _bankNameController.text,
        bankAccount: _bankAccountController.text,
      );

      widget.onStateChanged();
      EasyLoading.dismiss();
      EasyLoading.showSuccess("保存成功");
      if (mounted) {
        Navigator.pop(context);
      }
    } catch (e) {
      EasyLoading.dismiss();
      EasyLoading.showError("保存失败：${e.toString()}");
    }
  }

  // 只读模式提示
  Widget _buildReadOnlyTip() {
    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.blue.withOpacity(0.1),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.blue.withOpacity(0.3)),
      ),
      child: Row(
        children: [
          Icon(
            Icons.info_outline,
            color: Colors.blue,
            size: 20,
          ),
          const SizedBox(width: 8),
          Expanded(
            child: Text(
              '当前信息为只读状态，无法修改',
              style: TextStyle(
                color: Colors.blue.shade700,
                fontSize: 14,
              ),
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return NormalScaffold(
      title: '结算账户',
      child: Form(
        key: _formKey,
        child: ListView(
          padding: const EdgeInsets.all(ThemeVars.paddingPage),
          children: [
            // 只读提示
            if (widget.isReadOnly) _buildReadOnlyTip(),
            
            // 账户类型选择
            Container(
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(8),
                border: Border.all(color: ThemeVars.colorBorder),
              ),
              child: ListTile(
                title: Row(
                  children: [
                    const Text(
                      '账户类型',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    const Text(
                      ' *',
                      style: TextStyle(
                        color: Colors.red,
                        fontSize: 16,
                      ),
                    ),
                  ],
                ),
                subtitle: Text(
                  _settlementType.isEmpty 
                      ? '请选择账户类型' 
                      : _settlementTypeMap[_settlementType] ?? '未知类型',
                  style: TextStyle(
                    color: _settlementType.isEmpty 
                        ? ThemeVars.colorTextSec 
                        : Colors.black,
                    fontSize: 14,
                  ),
                ),
                trailing: widget.isReadOnly 
                    ? null 
                    : const Icon(Icons.arrow_forward_ios, size: 16),
                onTap: widget.isReadOnly ? null : _showAccountTypeOptions,
              ),
            ),
            
            const SizedBox(height: 16),
            
            // 开户银行
            TextFormField(
              controller: _bankNameController,
              enabled: !widget.isReadOnly,
              decoration: const InputDecoration(
                labelText: '开户银行',
                hintText: '请输入开户银行',
                suffixIcon: Icon(Icons.account_balance_outlined),
              ),
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return '请输入开户银行';
                }
                if (value.length < 2) {
                  return '银行名称长度不能小于2个字符';
                }
                if (value.length > 50) {
                  return '银行名称长度不能超过50个字符';
                }
                return null;
              },
            ),
            
            const SizedBox(height: 16),
            
            // 银行账号
            TextFormField(
              controller: _bankAccountController,
              enabled: !widget.isReadOnly,
              decoration: const InputDecoration(
                labelText: '银行账号',
                hintText: '请输入银行账号',
                suffixIcon: Icon(Icons.credit_card_outlined),
              ),
              keyboardType: TextInputType.number,
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return '请输入银行账号';
                }
                if (!RegExp(r'^\d{16,19}$').hasMatch(value)) {
                  return '请输入正确的银行账号';
                }
                return null;
              },
            ),
            
            const SizedBox(height: 24),
            
            // 只有在非只读模式下才显示保存按钮
            if (!widget.isReadOnly)
              SizedBox(
                width: double.infinity,
                height: 44,
                child: ElevatedButton(
                  onPressed: _saveForm,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: ThemeVars.colorPrimary,
                    foregroundColor: Colors.white,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                  child: const Text(
                    '保存',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }
} 